//
//  ViewController.m
//  A段项目
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "ViewController.h"
#import "NetWorkingHandler.h"
#import "Model.h"
#import <UIImageView+WebCache.h>
#import "WaterFlowLayout.h"
#import <MJRefresh.h>
#import "LeftMenuView.h"
#import <MBProgressHUD.h>
#import "TouchFirstView.h"

#import <MJRefreshComponent.h>

#import "HomePageCell.h"
#import "ViewForHeader.h"


#import "SearchResultView.h"

#import "LbtWebView.h"

#import "CollectViewController.h"

#import <DKNightVersion.h>

#define HEIGHT [UIScreen mainScreen].bounds.size.height




@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,WaterFlowDelegate,UISearchBarDelegate,UITableViewDelegate,ViewForHeaderDelegate>

@property (nonatomic, retain) NSMutableArray *arrModelUp;  //上方数据
@property (nonatomic, retain) NSMutableArray *arrModelBotoom;//底部数据
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) WaterFlowLayout *layout;
@property (nonatomic, retain) ViewForHeader *header;


@end

@implementation ViewController

{
    
    NSInteger num ;
}

- (void)dealloc {
    
     [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    self.layout.delegate = nil;
    self.collectionView.delegate = nil;
    
    self.header.delegate  = self;
    
    [_layout release];
    
    [_arrModelBotoom release];
    
    [_arrModelUp release];
    
    [_collectionView release];
    
    [_header release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    [self dataArray];
    
    
    [self handleData];
    
    [self createCollectionView]; //创建最底下的瀑布流.
    
    //右上角 收藏 button
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"xingxing"] style:0 target:self action:@selector(alreadyCollect)];
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self.collectionView.mj_header beginRefreshing];

    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:nil]; /*通知 ViewHeader 刷新;  当刷新时,ViewHeader 也刷新数据. */
        
        num = 1;
        
        [self handleData];
        
    }];
    
    
    /**上拉刷新.*/
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        num++;
        [self handleData];
        
        [self.collectionView reloadData];
        
       
    }];
    
    
    [self createView];
    
   

    
    
}

/**调用收藏的相册. */
- (void)alreadyCollect {
    

    
    CollectViewController *collect = [[CollectViewController alloc] init];
    
    
    
    [self.navigationController pushViewController:collect animated:YES];
    
    
    [collect release];
    
}


- (NSArray *)dataArray {
    
    if (self.arrModelBotoom == nil) {
        
        self.arrModelBotoom = [NSMutableArray array];
    }
    
    return self.arrModelBotoom;
}





#pragma mark -- 获取数据.
- (void)handleData {
    
    
      NSString *count = [NSString stringWithFormat:@"http://mapp.tiankong.com/index/bottom?pageNum=%ld&pageSize=20",num];
    
    [NetWorkingHandler netWorkingWithUrl:count complete:^(id result) {
        
        NSArray *arr = [NSArray array];
        
            arr = [result objectForKey:@"data"];
            
            for (NSDictionary *dic in arr) {
                
                Model *model = [[Model alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.arrModelBotoom addObject:model];
                
                [model release];
            
            }
        
        [self.collectionView reloadData];
        
        [self.collectionView.mj_footer endRefreshing];
        
        [self.collectionView.mj_header endRefreshing];
    }];
    
    
}

- (void)createCollectionView {
    
    self.layout = [[WaterFlowLayout alloc] init];
    
self.layout.number = [NSNumber numberWithFloat:1900];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:self.layout];
    
    
    
    self.layout.delegate = self;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    self.layout.insertItemSpacing = 5;

    self.collectionView.backgroundColor = [UIColor whiteColor];
    
        
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[HomePageCell class] forCellWithReuseIdentifier:@"pool1"]
    ;
    

    [_layout release];
    
    [_collectionView release];
    
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"kuang1"]];
    
    image.frame = CGRectMake(30, 2, self.collectionView.frame.size.width - 60, 50);
    
    [self.collectionView addSubview:image];
    
    image.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    
    [image addGestureRecognizer:tap];
    
    [tap addTarget:self action:@selector(tapAction:)];
    

}

- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    SearchResultView *searchView = [[SearchResultView alloc] init];
    
    [self.navigationController pushViewController:searchView animated:NO];
    
}

- (void)createView {
    

    self.header = [[ViewForHeader alloc] initWithFrame:CGRectMake(0, 45, self.view.frame.size.width, 1900)];
    
    self.header.delegate = self;

    [self.collectionView addSubview:self.header];
    
    [_header release];
  
}

- (void)highetForHeaderView:(CGFloat)height {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        
        self.header.frame = CGRectMake(0, 45, self.view.frame.size.width, height);
        
        self.layout.number = [NSNumber numberWithFloat:height + 45];
        
      
        /**直接更改布局不好用,所以移除重新建立*/
        [self.header removeFromSuperview];
        
        self.header = [[ViewForHeader alloc] initWithFrame:CGRectMake(0, 45, self.view.frame.size.width,height)];
        
        [self.collectionView addSubview:self.header];
        
    //    [self.collectionView reloadData];
        
        [_header release];
        

        
    });
    
    
    
    return;
    
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    

    return self.arrModelBotoom.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  
    Model *model = [self.arrModelBotoom objectAtIndex:indexPath.item];
    
    HomePageCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.url]];

    
    cell.backgroundColor = [UIColor whiteColor];
    
    
    return cell;
}

- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath {
    

  Model *model = [self.arrModelBotoom objectAtIndex:indexPath.item];
  
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 15)/2;
        
        self.layout.itemSize = CGSizeMake(w, w);
    
    CGFloat height = (model.height/model.width) * w ;
    
    return height;
    
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
  Model *modle =  [self.arrModelBotoom objectAtIndex:indexPath.item];
    
  
    
    /**网络解析进入到点击后的数据,得到进入下一层的接口. */
   [NetWorkingHandler netWorkingWithUrl:[NSString stringWithFormat:@"http://mapp.tiankong.com/imageUser/detail/v1.1?imageId=%ld&imageType=1",(long)modle.id] complete:^(id result) {
       
       NSDictionary *dic = [result objectForKey:@"data"];
       
       Model *model1 = [[Model alloc] init];
       
       [model1 setValuesForKeysWithDictionary:dic];
       
       /**继续解析数据. */
       [NetWorkingHandler netWorkingWithUrl:[NSString stringWithFormat:@"http://mapp.tiankong.com/search/similar?key=%@&pageNum=1&pageSize=50&tag=%@",modle.tag,model1.tag] complete:^(id result) {
           
     
    
           TouchFirstView *touchView = [[TouchFirstView alloc] init];
           
           [touchView setModalTransitionStyle:2];
           [touchView setModalPresentationStyle:1];
           
           NSDictionary *dic = [NSDictionary dictionaryWithDictionary:result];
           
           
           NSString *str = [NSString stringWithString:modle.url];
           
           NSDictionary *dic1 = [NSDictionary dictionaryWithObject:str forKey:@"url"];
           
           [touchView.array arrayByAddingObject:dic1];
           
           
           
           touchView.array = [NSMutableArray arrayWithArray:[dic objectForKey:@"data"]];
           
           [touchView.array insertObject:dic1 atIndex:0];
           
           
           [self presentViewController:touchView animated:YES completion:^{
               
               
           }];
           
           
           [touchView release];
           
       }];
       
   }];
    
    
  
    
    
}



    






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
   
    
    
    
}



@end
